package pub.tbc.toolkit.io;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @author tbc on 2016/9/23 1:09.
 */
@Slf4j
public class StreamHelper {

    private static void proException(String msg, Exception e) {
        msg = msg + " : " + e.getMessage();
        log.error(msg);
        throw new RuntimeException(msg, e);
    }

    public static InputStreamReader getInputStreamReader(InputStream inputStream, String charset) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("不被支持的编码格式：" + e.getMessage(), e);
        }
        return inputStreamReader;
    }

    public static BufferedReader getBufferdReader(InputStreamReader inputStreamReader) {
        return new BufferedReader(inputStreamReader);
    }

    public static String read(InputStreamReader inputStreamReader) {
        BufferedReader bufferedInputStream = new BufferedReader(inputStreamReader);
        StringBuilder sb = new StringBuilder();
        String str = null;
        try {
            while ((str = bufferedInputStream.readLine()) != null) {
                sb.append(str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return sb.toString();
    }

    public static String read(InputStream in, String charset) {
        return read(getInputStreamReader(in, charset));

    }

    public static String read(InputStream in) {
        return read(in, "utf-8");
    }

    public static String readToStringByCharset(InputStream inputStream, String charset) {
        Reader reader = null;
        try {
            reader = new InputStreamReader(inputStream, charset);
        } catch (UnsupportedEncodingException e) {
            proException("不被支持的编码类型", e);
        }
        assert reader != null : "Assert : reader is null";
        BufferedReader bf = new BufferedReader(reader);

        StringBuilder sb = new StringBuilder();
        while (true) {
            try {
                String str = bf.readLine();
                if (str == null) break;
                sb.append(str).append("\n");
            } catch (IOException e) {
                proException("IO异常", e);
            }
        }
        return sb.toString();
    }
}
